package com.szewec.ps.util;

import com.alibaba.fastjson.JSON;
import com.szewec.ps.model.DBBase;


import java.util.Iterator;
import java.util.List;

/**
 * list工具类
 */
public class ListUtil {
    /**
     * 根据下标获取对应位置的值
     */
    public static String getValueByIndex(List<String> list, Integer index) {
        String value = "";
        if (index == null || index == -1) {
            return value;
        } else {
            try {
                return list.get(index);
            } catch (IndexOutOfBoundsException e) {
                return value;
            }
        }
    }

    public static boolean isEmpty(List list) {
        return list == null || list.size() == 0;
    }

    public static boolean isNotEmpty(List list) {
        return !isEmpty(list);
    }

    /**
     * 插入或更新list中的元素
     */
    public static <T extends DBBase> void insertOrReplaceListItem(T t, List<T> list) {
        boolean didReplace = false;
        if (list.size() == 0) {
            list.add(t);
            return;
        }
        if (isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                if (StringUtils.isNotEmpty(list.get(i).getId()) && t.getId().equals(list.get(i).getId())) {
                    list.set(i, t);
                    didReplace = true;
                    break;
                }
            }
            if (!didReplace) {
                list.add(t);
            }
        }
    }

    /**
     * 删除list中的元素
     */
    public static <T extends DBBase> void removeItem(T t, List<T> list) {
        if (StringUtils.isEmpty(t.getId())) {
            return;
        }
        if (isNotEmpty(list)) {
            Iterator<T> iterator = list.iterator();
            while (iterator.hasNext()) {
                T obj = iterator.next();
                if (StringUtils.isNotEmpty(obj.getId()) && obj.getId().equals(t.getId())) {
                    iterator.remove();
                }
            }
        }
    }

    /**
     * 复制list
     */
    public static <T,E> void copyList(List<E> source,List<T> target,Class<T> targetClass){
        if (source != null && source.size()>0){
            for (E object:source){
                try {
                    T t = JSON.parseObject(JSON.toJSONString(object),targetClass);
                    target.add(t);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
